from presenter import basepresenter
from domain import document
from config import sitesettings

class EditDocumentPresenter(basepresenter.BasePresenter):

    def respondToGet(self):
        # get the document key
        if (self.request.get('key')):
            editdocument = self.doctask.getByKey(self.request.get('key'))
            self.template_values['document'] = editdocument
        else:
            editdocument = None
            settings = sitesettings.SiteSettings()
            self.template_values['defaultimage'] = settings.defaultdocumentimage

        # set up the page title
        page_title = self.sitetitle + ' - Add / Edit Document'
        self.template_values['page_title'] = page_title

        #get the view to draw the page
        self.view.showGetResponse(self.template_values)

    def respondToPost(self):
        if (self.request.get('action') == "Delete"):
            olddocument = self.doctask.getByKey(self.request.get('documentkey'))
            self.doctask.delete(olddocument)
        else:
            # populate a document object from the request
            newdocument = document.Document()
            if (self.request.get('documentkey')):
                newdocument = self.doctask.getByKey(self.request.get('documentkey'))
            if self.currentuser:
              newdocument.postedby = self.currentuser
            newdocument.title = self.request.get('title')
            newdocument.summary = self.request.get('summary')
            newdocument.categories = self.request.get('categories', allow_multiple=True)
            if (self.request.get('published')):
                newdocument.published = True
            else:
                newdocument.published = False
            location = self.request.get('location')
            if (location):
                newdocument.location = self.request.get('location')
            imageurl = self.request.get('imagelink')
            if (imageurl):
                newdocument.imagelink = self.request.get('imagelink')
            newdocument.pages = int(self.request.get('pages'))
            # create the task and save the article
            self.doctask.save(newdocument)
        #get the view to draw the page
        self.view.showPostResponse(self.template_values)